<?php
/**
 * 支付接口调测例子
 * ================================================================
 * index 进入口，方法中转
 * submitOrderInfo 提交订单信息
 * queryOrder 查询订单
 *
 * ================================================================
 */
require('Utils.class.php');
require('config/config.php');
require('class/RequestHandler.class.php');
require('class/ClientResponseHandler.class.php');
require('class/PayHttpClient.class.php');

Class Request{
    //$url = 'http://192.168.1.185:9000/pay/gateway';

    private $resHandler = null;
    private $reqHandler = null;
    private $pay = null;
    private $cfg = null;

    public function __construct(){
        $this->Request();
    }

    public function Request(){
        $this->resHandler = new ClientResponseHandler();
        $this->reqHandler = new RequestHandler();
        $this->pay = new PayHttpClient();
        $this->cfg = new Config();

        $this->reqHandler->setGateUrl($this->cfg->C('url'));
        $this->reqHandler->setKey($this->cfg->C('key'));
    }

    public function index(){
        $method = isset($_REQUEST['method'])?$_REQUEST['method']:'submitOrderInfo';

        switch($method){
            case 'submitOrderInfo'://提交订单
                $this->submitOrderInfo();
                break;
            case 'callback':
                $this->callback();
                break;
        }
    }

    /**
     * 提交订单信息
     */
    public function submitOrderInfo(){
		$gotourl = $_POST['gotourl'];
		unset($_POST['gotourl']);
        $this->reqHandler->setReqParams($_POST,array('method'));
        $this->reqHandler->setParameter('service','pay.weixin.wappay');//接口类型：pay.weixin.wappay
        $this->reqHandler->setParameter('mch_id',$this->cfg->C('mchId'));//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('version',$this->cfg->C('version'));

        //通知地址，必填项，接收平台通知的URL，需给绝对路径，255字符内格式如:http://wap.tenpay.com/tenpay.asp
        $notify_url = 'http://'.$_SERVER['HTTP_HOST'];
        $this->reqHandler->setParameter('notify_url',$notify_url.'/jiupay/request.php?method=callback');
	//$this->reqHandler->setParameter('notify_url','http://pay.ideanin.com/notify/notify.aspx');//通知回调地址，目前默认是空格，商户在测试支付和上线时必须改为自己的，且保证外网能访问到
	$this->reqHandler->setParameter('callback_url',$notify_url.$gotourl);
	//$this->reqHandler->setParameter('callback_url',$notify_url);
        $this->reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
		//$this->reqHandler->setParameter('sub_appid','wxdb077cbd82189896');

        $this->reqHandler->setParameter('device_info','AND_SDK');//应用类型
        $this->reqHandler->setParameter('mch_app_name','悟空APP内测分发平台');//应用名
        $this->reqHandler->setParameter('mch_app_id','com.tencent.wzryAND');//应用标识

        $this->reqHandler->createSign();//创建签名

        $data = Utils::toXml($this->reqHandler->getAllParameters());

        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
		//echo $this->reqHandler->getAllParameters();
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());

            if($this->resHandler->isTenpaySign()){
                //当返回状态与业务结果都为0时才返回支付链接，其它结果请查看接口文档
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                    //echo json_encode(array('pay_info'=>$this->resHandler->getParameter('pay_info')));
					header("Location: ".$this->resHandler->getParameter('pay_info'));
                    exit();
                }else{
                    //echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('err_code').' Error Message:'.$this->resHandler->getParameter('err_msg')));
					echo '<script>alert("'.$this->resHandler->getParameter('err_msg').'");history.back();</script>';exit;
                    exit();
                }
            }
            //echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message')));
			echo '<script>alert("'.$this->resHandler->getParameter('message').'");history.back();</script>';exit;
        }else{
            //echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
			echo '<script>alert("'.$this->pay->getErrInfo().'");history.back();</script>';exit;
        }
    }

    /**
     * 提供给平台的回调方法
     */
    public function callback(){
        $xml = file_get_contents('php://input');
        $this->resHandler->setContent($xml);
		//var_dump($this->resHandler->setContent($xml));
        $this->resHandler->setKey($this->cfg->C('key'));
        if($this->resHandler->isTenpaySign()){
            if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
				//echo $this->resHandler->getParameter('status');
				// //此处可以在添加相关处理业务，校验通知参数中的商户订单号out_trade_no和金额total_fee是否和商户业务系统的单号和金额是否一致，一致后方可更新数据库表中的记录。
				//更改订单状态
				$mmfile = 'h6_log.txt';
				$mmhandle = fopen($mmfile, 'a+'); 
				$str = 'out_trade_no: '.$this->resHandler->getParameter('out_trade_no').' total_fee: '.$this->resHandler->getParameter('total_fee');
				fwrite($mmhandle, date("Y-m-d H:i:s",time())." str: ".$str."\n");
				fclose($mmhandle);

				$out_trade_no = $this->resHandler->getParameter('out_trade_no');
				$_POST['total_amount'] = $this->resHandler->getParameter('total_fee');

				$dbconfig = require_once('../Application/Common/Conf/db.php');


				$downnum = 0;
				$taocanarray = array(
					'1'=>'10',
					'35'=>'1000',
					'100'=>'3000',
					'160'=>'5000',
					'300'=>'10000',
				);
				

				$con=mysqli_connect($dbconfig['DB_HOST'],$dbconfig['DB_USER'],$dbconfig['DB_PWD'],$dbconfig['DB_NAME']);
				mysqli_query($con,'set names utf8');
				// 检查连接
				if (!$con)
				{
					die("连接错误: " . mysqli_connect_error());
				}
				
				$sql="select * from lc_taocanorder where orderid='".$out_trade_no."'";

				$result = $con->query($sql);
				$row = $result->fetch_assoc();


				if($row && ($row['buymoney']*100)==$_POST['total_amount'] && $row['status']=='0'){
					$buymoney = (int)$row['buymoney'];

					if($row['paytype']=='1'){
						if(isset($taocanarray[$buymoney])){
						//if(1){

							$downnum = $taocanarray[$buymoney];
							//$downnum = 20;
							$rs1 = mysqli_query($con,"update lc_taocanorder set status=1 where orderid='".$out_trade_no."'");
							$rs2 = mysqli_query($con,"update lc_member set downnum=downnum+".$downnum." where id='".$row['userid']."'");

						}
					}elseif($row['paytype']=='2'){
						$rs1 = mysqli_query($con,"update lc_taocanorder set status=1 where orderid='".$out_trade_no."'");
						$rs2 = mysqli_query($con,"update lc_member set mymoney=mymoney+".$buymoney." where id='".$row['userid']."'");
					}

					if($row['listid']){
						$note = '购买APP';
					}else{
						$note = '购买套餐';
					}
					mysqli_query($con,"INSERT INTO lc_orders (orderno, userid, money, addtime, status, paytype, listid, note) 
					VALUES ('".$row['orderid']."', '".$row['userid']."', '".$row['buymoney']."', '".$row['addtime']."', '1', '".$row['paytype']."', '".$row['listid']."','".$note."')");
				}
				mysqli_close($con);  



                Utils::dataRecodes('接口回调收到通知参数',$this->resHandler->getAllParameters());
                echo 'success';
                exit();
            }else{
                echo 'failure';
                exit();
            }
        }else{
            echo 'failure';
        }
    }
}

$req = new Request();
$req->index();
?>